import 'package:casdon/app/config/env/common_config.dart';
import 'package:casdon/app/config/env/env_provider.dart';
import 'package:casdon/app_providers.dart';
import 'package:casdon/core/extentions/datetime_extern.dart';
import 'package:casdon/core/extentions/string_crypto.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:dio/dio.dart';

import 'package:uuid/uuid.dart';

class RuiyunInterceptor extends Interceptor {
  const RuiyunInterceptor();

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    final env = getProvider(environmentProvider);
    if (options.uri.authority != Uri.parse(env.ry_url).authority) {
      handler.next(options);
      return;
    }
    final queryDic = Map<String, dynamic>.from(options.queryParameters);
    queryDic['\$appid'] = CommonConfig.ry_appId;
    queryDic['\$tenant'] = CommonConfig.ry_tenant;
    queryDic['\$timestamp'] = DateTimeExtension.beijingTimestampInMillis;
    queryDic['\$reqid'] = Uuid().v4();

    // 1. 提取并排序所有 Key
    final sortedKeys = queryDic.keys.toList()..sort();
    Log.d("RuiyunInterceptor sortedKeys: $sortedKeys");

    // 2. 按 Key 顺序拼接所有 Value
    var signString = StringBuffer();
    for (final key in sortedKeys) {
      signString.write(queryDic[key].toString());
    }

    // 3. 追加 signKey
    signString.write(CommonConfig.ry_sign);
    Log.d("RuiyunInterceptor signString: $signString");

    final sign = signString.toString().sha256().toUpperCase();
    Log.d("RuiyunInterceptor sign: $sign");

    queryDic['\$sign'] = sign;
    options.queryParameters = queryDic;

    Log.d("RuiyunInterceptor Final URI: ${options.uri}"); // 空格变为%20，$符号保持原样
    handler.next(options);
  }
}
